import {
  Button,
  Form,
  FormItem,
  Image,
  Modal,
  Select,
  SelectOption,
  Space,
  TypographyText
} from 'ant-design-vue'
import { defineComponent, nextTick, onMounted, ref } from 'vue'

import { commonMenuApi, jindouLifeApi } from '@/apis'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { bus, optionsToMap } from '@/utils'
import { handlePrice } from '@/utils/bsshow'

import SetPrice from './setPrice'

export default defineComponent({
  name: 'JdlGoodsManage',
  setup() {
    const showSetPriceDlg = ref(false)
    const optionGoodsItemCur = ref({} as any)
    const selectLabelList = ref([] as any[])
    const showSetLabelDlg = ref(false)
    const setLabelDlgLoading = ref(false)

    const { showConfirm } = useDialog()
    const upDownStatusOptions = [
      { label: '下架', value: 0 },
      { label: '上架', value: 1 }
    ]

    const thirdStatusOptions = [
      { label: '下架', value: 0 },
      { label: '上架', value: 1 },
      { label: '售罄', value: 2 }
    ]

    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          slots: {
            buttons: 'batchButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '站点名称',
              field: 'city',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              title: '商品名称',
              field: 'productTitle',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              title: '我方状态',
              field: 'ourProductType',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: upDownStatusOptions
              }
            },
            {
              title: '第三方状态',
              field: 'productType',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: thirdStatusOptions
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100,
          resizable: true
        },
        checkboxConfig: {
          showHeader: true,
          range: true
        },
        columns: [
          {
            type: 'checkbox',
            width: 50
          },
          {
            title: '商品ID',
            field: 'id'
          },
          {
            title: '站点',
            field: 'city'
          },
          {
            title: '第三方产品ID',
            field: 'productId'
          },
          {
            title: '封面图片',
            slots: {
              default: 'image'
            }
          },
          {
            title: '标题',
            field: 'productTitle',
            width: 180
          },
          {
            title: '库存',
            field: 'channelStock'
          },
          {
            title: '销量',
            field: 'channelSaleAmount'
          },
          {
            title: '第三方状态',
            field: 'productType',
            formatter: ({ cellValue }) => {
              return optionsToMap(thirdStatusOptions)[cellValue]
            }
          },
          {
            title: '第三方门市价',
            field: 'originPrice',
            formatter: ({ cellValue }) => {
              return '￥' + cellValue
            }
          },
          {
            title: '第三方售价',
            field: 'salePrice',
            formatter: ({ cellValue }) => {
              return '￥' + cellValue
            }
          },
          {
            title: '初始售价',
            field: 'channelPrice',
            formatter: ({ cellValue }) => {
              return '￥' + cellValue
            }
          },
          {
            title: '销售价',
            width: 150,
            slots: {
              default: 'salePrice'
            }
          },
          {
            title: '我方状态',
            fixed: 'right',
            slots: {
              default: 'status'
            },
            width: 100
          },
          {
            title: '操作',
            fixed: 'right',
            slots: {
              default: 'operation'
            },
            width: 250
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              const data = await jindouLifeApi.getGoodsList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    onMounted(() => {
      bus.on('refreshJdlGoodsList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
      getLabelList()
    })

    //获取优惠券
    async function getLabelList() {
      try {
        selectLabelList.value = await commonMenuApi.getSelectLabelList()
      } catch {}
    }

    //获取选中的项
    function getSelectedItems() {
      return tableRef.value.table?.getCheckboxRecords()
    }

    //上下架操作
    function handleUpDown(item, toUp: boolean) {
      let ids = [] as any[]
      if (item) {
        ids.push(item.id)
      } else {
        ids = getSelectedItems().map(item => {
          return item.id
        })
      }
      showConfirm({
        content: toUp
          ? `确认上架${item ? '该' : '这些'}商品？`
          : `确认下架${item ? '该' : '这些'}商品？`,
        onOk: async () => {
          try {
            await jindouLifeApi.upDownGoods(ids, toUp ? 1 : 0)
            tableRef.value.refresh()
          } catch (error) {}
        }
      })
    }

    //设置价格
    function handleSetPrice(item) {
      optionGoodsItemCur.value = item
      showSetPriceDlg.value = true
    }

    //设置标签
    function handleSetLabel(item) {
      optionGoodsItemCur.value.productId = item.productId
      optionGoodsItemCur.value.locationId = item.locationId
      if (item.labels) {
        optionGoodsItemCur.value.labelIds = item.labels.map(item => item.id)
      } else {
        optionGoodsItemCur.value.labelIds = []
      }
      showSetLabelDlg.value = true
    }

    function onLabelChange(labels: string[]) {
      if (labels.length > 3) {
        labels.shift()
        optionGoodsItemCur.value.labelIds = labels
      }
    }

    async function setLabelConfirm() {
      try {
        setLabelDlgLoading.value = true
        await jindouLifeApi.setGoodsLebals(optionGoodsItemCur.value)
        tableRef.value.refresh()
        showSetLabelDlg.value = false
      } finally {
        setLabelDlgLoading.value = false
      }
    }

    return {
      tableRef,
      tableConfig,
      showSetPriceDlg,
      optionGoodsItemCur,
      showSetLabelDlg,
      setLabelDlgLoading,
      selectLabelList,
      setLabelConfirm,
      handleUpDown,
      handleSetPrice,
      onLabelChange,
      handleSetLabel,
      getSelectedItems
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            batchButtons: () => (
              <Space>
                <Button
                  type="primary"
                  onClick={() => this.handleUpDown(null, true)}
                  disabled={
                    !this.getSelectedItems() ||
                    this.getSelectedItems().length == 0
                  }
                >
                  批量上架
                </Button>
                <Button
                  type="primary"
                  disabled={
                    !this.getSelectedItems() ||
                    this.getSelectedItems().length == 0
                  }
                  onClick={() => this.handleUpDown(null, false)}
                >
                  批量下架
                </Button>
              </Space>
            ),
            image: ({ row }) => <Image src={row.faceImg}></Image>,
            status: ({ row }) => {
              return (
                <Space>
                  {row.ourProductType == 0 ? (
                    <TypographyText type="danger">下架</TypographyText>
                  ) : (
                    <TypographyText type="success">上架</TypographyText>
                  )}
                </Space>
              )
            },
            salePrice: ({ row }) => {
              return (
                <Space>{handlePrice(row.salesPrice, row.salesGoldBean)}</Space>
              )
            },
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleSetPrice(row)}
                >
                  设置价格
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleSetLabel(row)}
                >
                  设置标签
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() =>
                    this.handleUpDown(row, row.ourProductType === 0)
                  }
                >
                  {row.ourProductType === 0 ? '上架' : '下架'}
                </Button>
              </Space>
            )
          }}
          {...this.tableConfig}
        />
        <Modal
          v-model:visible={this.showSetPriceDlg}
          title="设置价格"
          destroyOnClose
          footer={null}
          width={1000}
          height={400}
        >
          <SetPrice
            goodsId={this.optionGoodsItemCur.productId}
            siteId={this.optionGoodsItemCur.locationId}
          ></SetPrice>
        </Modal>

        <Modal
          v-model:visible={this.showSetLabelDlg}
          confirmLoading={this.setLabelDlgLoading}
          title={'设置标签'}
          onOk={this.setLabelConfirm}
        >
          <Form labelCol={{ span: 4 }}>
            <FormItem label="设置标签" required>
              <Select
                mode="multiple"
                maxTagCount={3}
                v-model:value={this.optionGoodsItemCur.labelIds}
                style={{ width: '300px' }}
                placeholder="请选择"
                onChange={this.onLabelChange}
              >
                {this.selectLabelList.map(val => (
                  <SelectOption value={val.id}>{val.labelName}</SelectOption>
                ))}
              </Select>
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
})
